package com.example.petshopping.ui.address;

import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.petshopping.R;
import com.example.petshopping.ui.address.adapter.AddressAdapter;
import com.example.petshopping.ui.address.dialog.RegionPickerDialog;
import com.example.petshopping.ui.address.model.Address;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class AddressActivity extends AppCompatActivity implements AddressAdapter.OnAddressActionListener {

    private ImageView btnBack;
    private RecyclerView recyclerAddresses;
    private Button btnAddAddress;
    private LinearLayout layoutEmpty;
    
    private AddressAdapter addressAdapter;
    private List<Address> addressList;
    
    // 添加地址对话框相关
    private Dialog addAddressDialog;
    private EditText etName, etPhone, etDetailAddress;
    private TextView tvRegion;
    private CheckBox cbSetDefault;
    private Button btnSave;
    
    private String selectedProvince = "";
    private String selectedCity = "";
    private String selectedDistrict = "";
    
    // 当前正在编辑的地址
    private Address currentEditingAddress = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address);
        
        initViews();
        setupAdapter();
        loadAddresses();
        setupListeners();
    }
    
    private void initViews() {
        btnBack = findViewById(R.id.btn_back);
        recyclerAddresses = findViewById(R.id.recycler_addresses);
        btnAddAddress = findViewById(R.id.btn_add_address);
        layoutEmpty = findViewById(R.id.layout_empty);
    }
    
    private void setupAdapter() {
        addressList = new ArrayList<>();
        addressAdapter = new AddressAdapter(this, addressList);
        addressAdapter.setOnAddressActionListener(this);
        recyclerAddresses.setLayoutManager(new LinearLayoutManager(this));
        recyclerAddresses.setAdapter(addressAdapter);
    }
    
    private void loadAddresses() {
        // 此处应从SharedPreferences或后端API获取地址数据
        // 这里使用模拟数据
        addressList = generateSampleAddresses();
        addressAdapter.updateData(addressList);
        updateEmptyView();
    }
    
    private void updateEmptyView() {
        if (addressList.isEmpty()) {
            recyclerAddresses.setVisibility(View.GONE);
            layoutEmpty.setVisibility(View.VISIBLE);
        } else {
            recyclerAddresses.setVisibility(View.VISIBLE);
            layoutEmpty.setVisibility(View.GONE);
        }
    }
    
    private void setupListeners() {
        btnBack.setOnClickListener(v -> finish());
        
        btnAddAddress.setOnClickListener(v -> showAddAddressDialog(null));
    }
    
    private List<Address> generateSampleAddresses() {
        List<Address> addresses = new ArrayList<>();
        
        Address address1 = new Address(
                UUID.randomUUID().toString(),
                "房雪梅",
                "15210010866",
                "山东省",
                "济南市",
                "历下区",
                "浪潮科技园S06楼",
                true
        );
        addresses.add(address1);
        
        Address address2 = new Address(
                UUID.randomUUID().toString(),
                "房雪梅",
                "15210010866",
                "北京市",
                "北京市",
                "朝阳区",
                "恒基中心3层",
                false
        );
        addresses.add(address2);
        
        return addresses;
    }
    
    private void showAddAddressDialog(Address address) {
        // 保存当前编辑的地址
        currentEditingAddress = address;
        
        // 创建对话框
        addAddressDialog = new Dialog(this, R.style.DialogTheme);
        addAddressDialog.setContentView(R.layout.dialog_edit_address);
        
        // 初始化对话框中的控件
        TextView tvTitle = addAddressDialog.findViewById(R.id.tv_dialog_title);
        ImageView btnClose = addAddressDialog.findViewById(R.id.btn_dialog_close);
        etName = addAddressDialog.findViewById(R.id.et_name);
        etPhone = addAddressDialog.findViewById(R.id.et_phone);
        tvRegion = addAddressDialog.findViewById(R.id.tv_region);
        etDetailAddress = addAddressDialog.findViewById(R.id.et_detail_address);
        cbSetDefault = addAddressDialog.findViewById(R.id.cb_set_default);
        btnSave = addAddressDialog.findViewById(R.id.btn_save);
        ImageView btnLocation = addAddressDialog.findViewById(R.id.btn_location);
        
        // 设置标题
        if (address == null) {
            tvTitle.setText("添加收货地址");
            selectedProvince = "";
            selectedCity = "";
            selectedDistrict = "";
        } else {
            tvTitle.setText("修改收货地址");
            etName.setText(address.getName());
            etPhone.setText(address.getPhone());
            selectedProvince = address.getProvince();
            selectedCity = address.getCity();
            selectedDistrict = address.getDistrict();
            tvRegion.setText(address.getRegionText());
            etDetailAddress.setText(address.getDetailAddress());
            cbSetDefault.setChecked(address.isDefault());
        }
        
        // 设置监听器
        btnClose.setOnClickListener(v -> addAddressDialog.dismiss());
        
        tvRegion.setOnClickListener(v -> showRegionPicker());
        
        btnLocation.setOnClickListener(v -> {
            // 此处应打开定位功能，这里仅作示例
            Toast.makeText(this, "使用定位功能", Toast.LENGTH_SHORT).show();
        });
        
        btnSave.setOnClickListener(v -> {
            if (validateInput()) {
                saveAddress();
                addAddressDialog.dismiss();
            }
        });
        
        addAddressDialog.show();
    }
    
    private void showRegionPicker() {
        RegionPickerDialog dialog = new RegionPickerDialog(this);
        dialog.setSelectedRegion(selectedProvince, selectedCity, selectedDistrict);
        dialog.setOnRegionPickListener((province, city, district) -> {
            selectedProvince = province;
            selectedCity = city;
            selectedDistrict = district;
            tvRegion.setText(province + " " + city + " " + district);
        });
        dialog.show();
    }
    
    private boolean validateInput() {
        String name = etName.getText().toString().trim();
        String phone = etPhone.getText().toString().trim();
        String region = tvRegion.getText().toString().trim();
        String detailAddress = etDetailAddress.getText().toString().trim();
        
        if (name.isEmpty()) {
            Toast.makeText(this, "请输入收货人姓名", Toast.LENGTH_SHORT).show();
            return false;
        }
        
        if (phone.isEmpty() || phone.length() != 11) {
            Toast.makeText(this, "请输入正确的手机号码", Toast.LENGTH_SHORT).show();
            return false;
        }
        
        if (region.isEmpty() || "点击选择".equals(region)) {
            Toast.makeText(this, "请选择所在地区", Toast.LENGTH_SHORT).show();
            return false;
        }
        
        if (detailAddress.isEmpty()) {
            Toast.makeText(this, "请输入详细地址", Toast.LENGTH_SHORT).show();
            return false;
        }
        
        return true;
    }
    
    private void saveAddress() {
        String name = etName.getText().toString().trim();
        String phone = etPhone.getText().toString().trim();
        String detailAddress = etDetailAddress.getText().toString().trim();
        boolean isDefault = cbSetDefault.isChecked();
        
        if (currentEditingAddress == null) {
            // 添加新地址
            Address newAddress = new Address(
                    UUID.randomUUID().toString(),
                    name,
                    phone,
                    selectedProvince,
                    selectedCity,
                    selectedDistrict,
                    detailAddress,
                    isDefault
            );
            
            // 处理默认地址逻辑
            if (isDefault) {
                for (Address address : addressList) {
                    address.setDefault(false);
                }
            }
            
            addressList.add(newAddress);
            addressAdapter.updateData(addressList);
            Toast.makeText(this, "地址添加成功", Toast.LENGTH_SHORT).show();
        } else {
            // 编辑现有地址
            currentEditingAddress.setName(name);
            currentEditingAddress.setPhone(phone);
            currentEditingAddress.setProvince(selectedProvince);
            currentEditingAddress.setCity(selectedCity);
            currentEditingAddress.setDistrict(selectedDistrict);
            currentEditingAddress.setDetailAddress(detailAddress);
            
            // 处理默认地址逻辑
            if (isDefault && !currentEditingAddress.isDefault()) {
                for (Address address : addressList) {
                    address.setDefault(false);
                }
                currentEditingAddress.setDefault(true);
            }
            
            addressAdapter.updateData(addressList);
            Toast.makeText(this, "地址修改成功", Toast.LENGTH_SHORT).show();
        }
        
        updateEmptyView();
    }

    @Override
    public void onDeleteClick(Address address) {
        new AlertDialog.Builder(this)
                .setTitle("删除地址")
                .setMessage("确定要删除该地址吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    addressList.remove(address);
                    addressAdapter.removeAddress(address);
                    updateEmptyView();
                    Toast.makeText(this, "地址已删除", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", null)
                .show();
    }

    @Override
    public void onEditClick(Address address) {
        showAddAddressDialog(address);
    }

    @Override
    public void onCopyClick(Address address) {
        String fullAddress = address.getContactInfo() + " " + address.getFullAddress();
        
        ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText("地址", fullAddress);
        clipboard.setPrimaryClip(clip);
        
        Toast.makeText(this, "地址已复制", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onSetDefaultClick(Address address) {
        for (Address addr : addressList) {
            addr.setDefault(addr.equals(address));
        }
        
        addressAdapter.setDefaultAddress(address);
        Toast.makeText(this, "已设为默认地址", Toast.LENGTH_SHORT).show();
    }
} 